package com.cuitrip.business.home.recommend;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.cuitrip.apiservice.TrackBusiness;
import com.cuitrip.apiservice.TripBusiness;
import com.cuitrip.business.home.recommend.model.HomeCard;
import com.cuitrip.business.home.recommend.model.ListResponse;
import com.cuitrip.business.home.recommend.ui.CardItemHolderView;
import com.cuitrip.business.search.SearchActivity;
import com.cuitrip.business.track.TrackProxy;
import com.cuitrip.business.tripservice.ui.IconTextView;
import com.cuitrip.component.autoload.AutoLoadScrollListener;
import com.cuitrip.component.statelayout.StateLayout;
import com.cuitrip.service.R;
import com.cuitrip.util.ListUtil;
import com.lab.adapter.BaseHolderView;
import com.lab.adapter.HolderViewAdapter;
import com.lab.adapter.animation.SwingBottomInAnimationAdapter;
import com.lab.app.BaseFragment;
import com.lab.jumper.Jumper;
import com.lab.network.config.CtResponseCode;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;
import com.lab.utils.DisplayUtil;
import com.lab.utils.MessageUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.Bind;
import butterknife.OnClick;

public class RecommendCardListFragment extends BaseFragment implements IProxyCallback,SwipeRefreshLayout.OnRefreshListener, Runnable, AutoLoadScrollListener.PositionCallBack {

    private static final String TAG = "RecommendCardListFragment";

    private View mContentView;

    @Bind(R.id.ct_list)
    ListView mListView;

    @Bind(R.id.refresh_layout)
    SwipeRefreshLayout refreshLayout;

    @Bind(R.id.search_icon)
    IconTextView mSearchIcon;

    @Bind(R.id.search_box)
    TextView mSearchBox;

    @Bind(R.id.search_layout)
    LinearLayout mSearchLayout;

    @Bind(R.id.state_layout)
    StateLayout mStateLayout;

    private boolean isShowSearchBox = true;

    private HolderViewAdapter adapter;

    private List<HomeCard> cardList = new ArrayList<>();

    private int start;

    public static final  int PAGE_SIZE = 10;

    private AutoLoadScrollListener autoLoadScrollListener = new AutoLoadScrollListener(this, this);

    private ApiProxy mApiProxy = new ApiProxy(this);

    /**
     * The Fragment's UI is just a simple text view showing its
     * instance number.
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (mContentView == null) {
            mContentView = inflater.inflate(R.layout.recommend_card_list_view, container, false);
        } else {
            ViewParent parent = mContentView.getParent();
            if (parent != null) {
                ((ViewGroup) parent).removeView(mContentView);
            }
        }
        ButterKnife.bind(this, mContentView);
        autoLoadScrollListener.setLoadingView(ListUtil.setupLoadingFooter(inflater,mListView));
        initView();
        initListener();
        initData();
        return mContentView;
    }

    @OnClick(R.id.search_layout)
    protected void gotoSearch() {
        Jumper.launchActivity(getActivity(), new Intent(getActivity(), SearchActivity.class));
    }

    private void toggleSearchBox(boolean show) {
        if (isShowSearchBox != show) {
            this.isShowSearchBox = show;
            if (isShowSearchBox) {
                FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) mSearchLayout.getLayoutParams();
                layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT;
                layoutParams.height = DisplayUtil.dip2px(44.f);
                mSearchLayout.setLayoutParams(layoutParams);
                mSearchLayout.setBackgroundResource(R.drawable.search_white_corner_grey_stoke);
                mSearchBox.setVisibility(View.VISIBLE);
            } else {
                FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) mSearchLayout.getLayoutParams();
                layoutParams.width = DisplayUtil.dip2px(44.f);
                layoutParams.height = DisplayUtil.dip2px(44.f);
                mSearchLayout.setLayoutParams(layoutParams);
                mSearchLayout.setBackgroundResource(R.drawable.circle_white_grey_stoke);
                mSearchBox.setVisibility(View.GONE);

            }

        }
    }

    private void initView() {
        adapter = new HolderViewAdapter(getActivity(), cardList, CardItemHolderView.class);
        adapter.setHolderViewCallback(new HolderViewAdapter.HolderViewCallback() {
            @Override
            public void onHolderViewInvalidate(BaseHolderView holderView, int position) {
                if (holderView instanceof CardItemHolderView) {
                    CardItemHolderView cardItemHolderView = (CardItemHolderView) holderView;
                    cardItemHolderView.setPage(cardList.size()/ PAGE_SIZE);
                    cardItemHolderView.setCurrentList(cardList);
                }

            }
        });
        SwingBottomInAnimationAdapter swingBottomInAnimationAdapter = new SwingBottomInAnimationAdapter(adapter);
        swingBottomInAnimationAdapter.setAbsListView(mListView);
        swingBottomInAnimationAdapter.setAnimationDurationMillis(500);
        mListView.setAdapter(swingBottomInAnimationAdapter);
    }

    private void initListener() {
        mListView.setOnScrollListener(autoLoadScrollListener);
        refreshLayout.setOnRefreshListener(RecommendCardListFragment.this);
    }

    private void initData() {
        mStateLayout.changeState(StateLayout.State.Loading);
        mStateLayout.setOnClickStateLayoutListener(new StateLayout.OnClickStateLayoutListener() {
            @Override
            public void onClick(StateLayout.State state) {
               refreshList();
            }
        });
        mContentView.post(new Runnable() {
            @Override
            public void run() {
                refreshList();
            }
        });
    }

    private void inflateList(List<HomeCard> tempList, boolean isMore) {
        if (start == 0) {
            cardList.clear();
        }
        cardList.addAll(tempList);
        adapter.notifyDataSetChanged();
        autoLoadScrollListener.setEnable(isMore);
    }

    private void showRefreshing() {
        if (refreshLayout != null) {
            refreshLayout.setRefreshing(true);
        }
    }

    private void hideRefreshing() {
        if (refreshLayout != null) {
            refreshLayout.setRefreshing(false);
        }
    }

    @Override
    public void onRefresh() {
        showRefreshing();
        refreshList();
    }

    private void refreshList(){
        start = 0;
        autoLoadScrollListener.setEnable(false);
        TripBusiness.getRecommendCardList(mApiProxy,true,start,PAGE_SIZE);
    }


    public void onDestroy() {
        super.onDestroy();
        hideRefreshing();
    }

    @Override
    public void run() {
        autoLoadScrollListener.setEnable(false);
        start = cardList.size();
        autoLoadScrollListener.onLoadChanged(true);
        TripBusiness.getRecommendCardList(mApiProxy, true, start, PAGE_SIZE);
    }

    @Override
    public void onScrollTop() {
        toggleSearchBox(true);
    }

    @Override
    public void onScrollLeftTop() {
        toggleSearchBox(false);
    }

    @Override
    public boolean onProxyResult(ProxyResult<?> result) {
        hideRefreshing();
        CtApiResponse response = (CtApiResponse) result.getData();
        autoLoadScrollListener.onLoadChanged(false);
        if (response!= null && response.code == CtResponseCode.RESULT_OK){
            if (response.result instanceof ListResponse) {
                ListResponse<HomeCard> cardListResponse = (ListResponse<HomeCard>) response.result;
                inflateList(cardListResponse.getList(), cardListResponse.isMore());
                List<String> ids = new ArrayList<String>();
                for (HomeCard card : cardListResponse.getList()) {
                    ids.add(String.valueOf(card.getId()));
                }
                mStateLayout.changeState(StateLayout.State.INIT);
                TrackProxy.getInstance().operationAction(TrackBusiness.Source.RECOMMEND, TrackBusiness.Action.REVIEW, String.valueOf(cardList.size()/ PAGE_SIZE), "", ids);
            }
        }else{
            if (response != null && !TextUtils.isEmpty(response.msg)) {
                MessageUtils.showToast(response.msg);
            }
            mStateLayout.changeState(StateLayout.State.NoNetwork);
        }
        return false;
    }



}
